package org.example.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.TypeReference;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.example.entity.UserInfo;
import org.example.mapper.UserInfoMapper;
import org.example.model.mysql.Account;
import org.example.model.mysql.ItemInfo;
import org.example.service.UserInfoService;
import org.example.utils.RandomUtils;
import org.springframework.stereotype.Service;

import java.time.Instant;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author huangy
 * @description
 * @since 2022/11/11 17:37
 **/
@Service
@Slf4j
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {

    @Override
    public UserInfo getUserInfo(long id) {
        UserInfo userInfo = this.getById(id);
        System.out.println(userInfo);
        return userInfo;
    }

    @Override
    public List<UserInfo> getUserInfos() {
        return this.getUserInfos(10000);
    }

    @Override
    public void updateUserInfo(long id) {
        UserInfo userInfo = this.getById(id);
        Map<Integer, ItemInfo> items = JSON.parseObject(userInfo.getItems(), new TypeReference<Map<Integer, ItemInfo>>(){});
        items.forEach((itemId, itemInfo) -> {
            itemInfo.setExpireTime(LocalDateTime.now());
            itemInfo.setNum(Instant.now().toEpochMilli());
        });
        userInfo.setItems(JSON.toJSONString(items));
        Account account = JSON.parseObject(userInfo.getAccount(), Account.class);
        account.setNick(RandomUtils.randomChineseName());
        account.setGender(RandomUtils.randomZeroOrOne());
        userInfo.setAccount(JSON.toJSONString(account));
        this.saveOrUpdate(userInfo);
    }

    @Override
    public void updateUserInfos() {
        List<UserInfo> userInfos = getUserInfos(1000);
        this.saveOrUpdateBatch(userInfos);
    }

    private List<UserInfo> getUserInfos(int num) {
        List<Long> userIds = new ArrayList<>();
        long id = 100000010;
        for (int i = 0; i < num; i++) {
            userIds.add(id++);
        }
        return this.listByIds(userIds);
    }
}
